package com.ignou.mca.evote;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ignou.mca.beans.Message;
import com.ignou.mca.beans.UserVO;
import com.ignou.mca.beans.CastVoteFormBean;
import com.ignou.mca.datasource.DataBaseUtilities;
import com.ignou.mca.datasource.Encryption;
import com.ignou.mca.datasource.VotingConstants;
import com.ignou.mca.util.SessionUtil;

public class Login extends HttpServlet implements Servlet {
	static String Name = "";

private DataBaseUtilities dbu = null;

	public Login() {
		super();
	}

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
		ServletContext context = getServletContext();
		Message message = new Message();
		HttpSession session = null;
		
		try {
			String UserName = req.getParameter("username");
			String password = req.getParameter("password");
			
			dbu = new DataBaseUtilities();
			UserVO st = null;
			st = dbu.doLogin(UserName, password, message);
			
			//String decryptedPwd = ""; 
			//if(st!=null) decryptedPwd = Encryption.decrypt(st.getPassword());
			
			if(st != null && st.getPassword().equals(password))
			{
				session = req.getSession();
				session.setAttribute("Message", message);
				if(st.getRole().equalsIgnoreCase("admin"))
				{
					session.setAttribute("UserVO", st);
					session.setAttribute("UserName", UserName);
					context.getRequestDispatcher("/AdminMenu.jsp").forward(req, resp);
				}
				else if(st!=null && st.getRole().equalsIgnoreCase("user") && st.getActiveStatus().equalsIgnoreCase("active"))
				{
					session.setAttribute("UserVO", st);
					context.getRequestDispatcher("/VotersMenu.jsp").forward(req, resp);
				}
			}else
			{
				message.setMessage(VotingConstants.LOGIN_FAILED);
				req.setAttribute("ErrorMessage", "LoginFailed");
				context.getRequestDispatcher("/ErrorPage.jsp").forward(req, resp);
			}
		} catch (Exception e) {
			req.setAttribute("ErrorMessage", "LoginFailed");
			try {
				context.getRequestDispatcher("/ErrorPage.jsp").forward(req, resp);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
			e.printStackTrace();
			
		} 
	}
}